﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;
using MS.InformationManagement.DAL.DocumentCenter;
using MS.InformationManagement.Support;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
//using DocumentFormat.OpenXml.Wordprocessing;
using System.IO;
using System.Globalization;
using System.Collections;
using MS.InformationManagement.Support.Enums;
using DocumentFormat.OpenXml.Wordprocessing;
using MS.InformationManagement.Support.FileCreator;
//using iTextSharp.text.pdf;

namespace MS.InformationManagement.BLL.ActasDeAnulacion
{
    public class ActasDeAnulacion
    {
        public static List<Radicado> getRadicadosAnulados(int pageIndex, int pageSize, out int totalRecords, bool isUpdate)
        {
            int startingPosition = pageIndex * pageSize;
            List<Radicado> foundAnulados = new List<Radicado>();
            
            using (var dc = new DCDocumentCenterDataContext(SPContext.Current.Web.Url))
            {
                foundAnulados = (from rdc in dc.GetList<Radicado>(GlobalConstants.LIST_ANULADOS)
                                 where rdc.NoActa == null ||
                                  rdc.NoActa == string.Empty
                                 select rdc).ToList();
            }
            if (foundAnulados == null)
            {
                totalRecords = 0;
                return null;
            }

            totalRecords = foundAnulados.Count();
            if (isUpdate)
                return foundAnulados;
            else
                return foundAnulados.Skip(startingPosition).Take(pageSize).ToList();
        }

        public static bool GenerarActaAnulacion(int pageIndex, int pageSize, out int totalRecords)
        {
            bool result = false;
            List<Radicado> foundAnulados = getRadicadosAnulados(pageIndex, pageSize, out totalRecords, true);
            if (foundAnulados != null)
            {
                string documentLibraryTemplate = GlobalConstants.LIST_TEMPLATE_REPORTES;
                string TemplateFileName =GlobalConstants.TEMPLATE_REPORT_ACTA_ANULACION;
                string documentDestinyLibraryName =GlobalConstants.LIST_ACTAS_DE_ANULACION;

                Hashtable Content = new Hashtable();
                Content.Add("##NumeroActa", new FileCreator { Text = getNumeroActa(), FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Center, isBold = true });
                Content.Add("##Periodo", new FileCreator { Text = DateTime.Now.ToShortDateString(), FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Center, isBold = true });
                Content.Add("##dia", new FileCreator { Text = DateTime.Now.Day.ToString(), FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Left, isBold = true });
                Content.Add("##Mes", new FileCreator { Text = DateTime.Now.ToString("MMMM", new CultureInfo("es-ES")), FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Left, isBold = true });
                Content.Add("##Año", new FileCreator { Text = DateTime.Now.Year.ToString(), FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Left, isBold = true });
                Content.Add("##Nombre", new FileCreator { Text = SPContext.Current.Web.CurrentUser.Name, FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Left, isBold = true });
                Content.Add("##TablaRadicados", new FileCreator { Element = CrearTablaRadicados(foundAnulados), FontName = fontName.Arial, FontSize = 20, HorizontallyAlign = JustificationValues.Left, isBold = true });
                

                string idActa = OfficeWordHelper.GenerarWordFromTemplate(documentLibraryTemplate, TemplateFileName, documentDestinyLibraryName, Content);
                if (!string.IsNullOrEmpty(idActa))
                {
                    foreach (Radicado radicados in foundAnulados)
                    {
                        updateRadicadoActa(radicados, idActa);
                    }
                }

                result = true;
            }

            return result;
        }

        private static DocumentFormat.OpenXml.Wordprocessing.Table CrearTablaRadicados(List<Radicado> foundAnulados)
        {

            DocumentFormat.OpenXml.Wordprocessing.Table table = new DocumentFormat.OpenXml.Wordprocessing.Table();

            TableProperties tblProp = new TableProperties(
                new TableBorders(
                    new TopBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
                    new BottomBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
                    new LeftBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
                    new RightBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
                    new InsideHorizontalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 },
                    new InsideVerticalBorder() { Val = new EnumValue<BorderValues>(BorderValues.Single), Size = 2 }
                )
            );


            table.AppendChild<TableProperties>(tblProp);

            // Create a row.
            DocumentFormat.OpenXml.Wordprocessing.TableRow tr = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
            // Create a cell.
            DocumentFormat.OpenXml.Wordprocessing.TableCell tc1 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
            tc1.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
            //tc1.Append(new Paragraph(new Run(new Text("Dependencia"))));
            tc1.Append(addParagraph("Dependencia", false));
            tr.Append(tc1);

            DocumentFormat.OpenXml.Wordprocessing.TableCell tc2 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
            tc2.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
            tc2.Append(addParagraph("Radicado", false));
            tr.Append(tc2);


            DocumentFormat.OpenXml.Wordprocessing.TableCell tc3 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
            tc3.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
            tc3.Append(addParagraph("Fecha de solicitud", false));
            tr.Append(tc3);

            DocumentFormat.OpenXml.Wordprocessing.TableCell tc4 = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
            tc4.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
            tc4.Append(addParagraph("Observacion solicitante", false));
            tr.Append(tc4);


            table.Append(tr);

            foreach (Radicado radicados in foundAnulados)
            {

                DocumentFormat.OpenXml.Wordprocessing.TableRow trRadicados = new DocumentFormat.OpenXml.Wordprocessing.TableRow();

                DocumentFormat.OpenXml.Wordprocessing.TableCell tcRadicadoDapendencia = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                tcRadicadoDapendencia.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
                tcRadicadoDapendencia.Append(addParagraph(getSeccionsById(radicados.DepartamentoUsuario.ToString()), false));
                trRadicados.Append(tcRadicadoDapendencia);

                DocumentFormat.OpenXml.Wordprocessing.TableCell tcRadicadoID = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                tcRadicadoID.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
                tcRadicadoID.Append(addParagraph(radicados.DocumentIDValue, false));
                trRadicados.Append(tcRadicadoID);


                DocumentFormat.OpenXml.Wordprocessing.TableCell tcFecha = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                tcFecha.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
                tcFecha.Append(addParagraph(DateTime.Now.ToShortDateString(), false));
                trRadicados.Append(tcFecha);

                DocumentFormat.OpenXml.Wordprocessing.TableCell tcObservacion = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
                tcObservacion.Append(new TableCellProperties(new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "2400" }));
                tcObservacion.Append(addParagraph(radicados.Observaciones, false));
                trRadicados.Append(tcObservacion);

                table.Append(trRadicados);
            }

            return table;
        }

        private static Paragraph addParagraph(string Text, bool isBold)
        {
            ParagraphProperties paragraphProperties = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties();

            //DocumentFormat.OpenXml.Wordprocessing.HorizontalAlignmentValues.Center

            Paragraph testParagraph = new Paragraph(new Run(new Text("")));
            Run run = testParagraph.AppendChild(new Run());
            RunProperties runProperties = run.AppendChild(new RunProperties());

            RunFonts runFont = new RunFonts();
            runFont.Ascii = "Arial";

            Bold bold1 = new Bold();

            DocumentFormat.OpenXml.Wordprocessing.FontSize fontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
            fontSize.Val = "20";

            if (isBold)
                runProperties.AppendChild(bold1);


            runProperties.AppendChild(fontSize);
            runProperties.AppendChild(runFont);
            run.AppendChild(new Text(Text));

            return testParagraph;
        }

        public static string getSeccionsById(string IdSeccion)
        {
            string result = string.Empty;
            if (ListHelper.TryToParse(IdSeccion) != 0)
            {
                SPUserToken systoken = SPContext.Current.Site.SystemAccount.UserToken;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url, systoken))
                    {
                        using (SPWeb currentWeb = currentSite.OpenWeb())
                        {
                            SPList listSecciones = currentWeb.Lists.TryGetList(GlobalConstants.LIST_BIBLIOTECA_SECCION);
                            if (listSecciones != null)
                            {
                                SPListItem item = listSecciones.GetItemById(int.Parse(IdSeccion));
                                if (item != null)
                                {
                                    result = item.Title;
                                }
                            }
                        }
                    }
                });
            }
            
            return result;
        }

        private static void updateRadicadoActa(Radicado radicados, string idActa)
        {
            SPUserToken systoken = SPContext.Current.Site.SystemAccount.UserToken;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url, systoken))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {
                        currentWeb.AllowUnsafeUpdates = true;
                        SPList listaRadicado = currentWeb.Lists[radicados.ListId];
                        SPList listaActasAnulacion = currentWeb.Lists[GlobalConstants.LIST_ACTAS_DE_ANULACION];

                        
                        SPListItem itemRadicado = listaRadicado.GetItemById(int.Parse(radicados.Id.ToString()));
                        itemRadicado[CustomSiteColumns.FIELD_DOCUMENT_ACTA_ID] = idActa;
                        itemRadicado.Update();
                        currentWeb.AllowUnsafeUpdates = false;
                    }
                }
            });
        }

        public static string getNumeroActa()
        {
            string result = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite currentSite = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb currentWeb = currentSite.OpenWeb())
                    {

                        SPList listaActasAnulacion = currentWeb.Lists[GlobalConstants.LIST_ACTAS_DE_ANULACION];
                        result = (listaActasAnulacion.ItemCount + 1).ToString();
                    }
                }
            });
            return result;
        }

    }
}
  